<template>
   
  <div class="expert-page  justify-center  min-h-screen pb-16 max-w-[1600px] mx-auto relative mt-16" >
  <!-- <div class="expert-page flex gap-8 justify-center  min-h-screen pb-16 max-w-[1600px] mx-auto " > -->
     
    <el-button class="!absolute -left-2 -top-12 z-10" @click="$router.back()" type="text" size="large">
          <el-icon><Back /></el-icon> 返回
        </el-button>

        <div class="recommend-title flex items-center gap-2 mb-4">
                <span class="font-bold text-xl text-blue-800">统计</span>
                <div class="h-2 w-2 rounded-full bg-gradient-to-r from-blue-400 to-blue-600"></div>
                <div class="flex-1 h-px bg-gradient-to-r from-blue-200 to-transparent"></div>
            </div>
            <div >
              <ExpertStatistics />
            </div>
        </div>
    <!-- 标签云 -->
    <!-- <ExpertTagCloud :tags="tagStats" :active-tag="activeTag" :tag-color="tagColor" @select="selectTag" class="w-[280px] flex-shrink-0 " /> -->
  <!-- <Question v-if="activeTab === 'qa'" /> -->
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useExpertListQuery } from '@/composables/useExpertDataQuery'
import { getSpecialtyTag,getSpecialtyTagTree } from '@/axios/api/expert'
import ExpertCard from './components/ExpertCard.vue'
import ExpertTagCloud from './components/ExpertTagCloud.vue'
import ExpertFilterBar from './components/ExpertFilterBar.vue'
import ExpertSkeleton from './components/ExpertSkeleton.vue'
import 'vue3-virtual-scroller/dist/vue3-virtual-scroller.css'
import { getQuestionHotTag } from '@/axios/api/question'
import ExpertStatistics from './components/ExpertStatistics.vue'
import avatar from '@/assets/avatar.png'  
import { Back, ChatDotRound, StarFilled } from '@element-plus/icons-vue'

import Question from '@/views/Question/Question.vue'
import w1 from '@/assets/w1.png'
import w2 from '@/assets/w2.png'
import z1 from '@/assets/z1.png'
import z2 from '@/assets/z2.png'



const router = useRouter()
const defaultAvatar = avatar

// 专业领域标签列表
const specialtyTags = ref([])

// 获取专业领域标签树
const fetchSpecialtyTags = async () => {
  try {
    const res = await getSpecialtyTagTree()
    if (res.code === 0 && res.data) {
      specialtyTags.value = res.data
    }
  } catch (error) {
    console.error('获取专业领域标签树失败:', error)
  }
}

// 在组件挂载时获取专业领域标签
onMounted(() => {
  const activeTab = sessionStorage.getItem('activeTab')

  if (activeTab) {
    handleActiveTabChange(activeTab)
  }
  fetchSpecialtyTags()
})

const search = ref('')
const selectedField = ref('')
const sortType = ref('')
const currentPage = ref(1)
const pageSize = 10
const activeTag = ref('')
const activeTab = ref('expert')
// 请求参数
const queryParams = computed(() => ({
  status: '', // 默认状态为1
  keyword: search.value,
  activeSort: '',
  specialtyTagIds: Array.isArray(selectedField.value) ? selectedField.value.join(',') : selectedField.value,
  limit: pageSize,
  page: currentPage.value
}))

// 使用 vue-query 获取专家列表
const { data: expertData, isLoading, refetch } = useExpertListQuery(queryParams)

// 监听分页变化
watch(currentPage, () => {
  refetch()
}, { flush: 'post' })

// 从响应中获取专家列表和总数
const experts = computed(() => {
  const records = expertData.value?.data?.list || []
  return records.map(expert => ({
    ...expert,
    id: expert.id,
    name: expert.name,
    field: typeof expert.specialtyTagNames === 'string' ? expert.specialtyTagNames : (expert.specialtyTagNames || ''),  // 专业领域
    fieldIds: typeof expert.specialtyTagNames === 'string' ? expert.specialtyTagNames : (expert.specialtyTagNames || ''),  // 专业领域
    org: expert.orgName || '',            // 单位
    title: expert.honor || '',            // 职称/荣誉
    intro: expert.introduction || '',      // 简介
    contact: expert.contact || '',         // 联系方式
    email: expert.email || '',            // 邮箱
    avatar: expert.avatar || defaultAvatar, // 头像
    createTime: expert.createTime,        // 创建时间
    updateTime: expert.updateTime         // 更新时间
  }))
})

const total = computed(() => expertData.value?.data?.totalCount || 0)



const tagColorMap = ['success', 'info', 'warning', 'danger', 'primary']
function tagColor(tag) {
  let hash = 0
  for (let i = 0; i < tag.length; i++) hash += tag.charCodeAt(i)
  return tagColorMap[hash % tagColorMap.length]
}

const allFields = computed(() => specialtyTags.value)
const sortOptions = [
  { label: '推荐排序', value: 'recommend' },
  { label: '答复数最多', value: 'reply' },
  { label: '最佳答案率最高', value: 'bestRate' },
  { label: '最新入驻', value: 'newest' },
]

// 由于使用了后端分页，不再需要前端过滤
const filteredExperts = computed(() => experts.value)
console.log(filteredExperts.value);

// 由于使用了后端分页，直接使用接口返回的数据
const pagedExperts = computed(() => filteredExperts.value)

const tagStats = ref([])

// 获取热门标签数据
const fetchHotTags = async () => {
  try {
    const res = await getQuestionHotTag()
    if (res.code === 0 && res.data) {
      // 将接口返回的数据结构转换为组件需要的格式
      tagStats.value = res.data.map(tag => ({
        name: tag.tagName,        // 标签名称
        count: tag.questionCount,  // 问题数量
        id: tag.tagId                // 添加标签ID
      }))
    }
  } catch (error) {
    console.error('获取热门标签失败:', error)
  }
}


// 在组件挂载时获取热门标签
onMounted(() => {
  fetchSpecialtyTags()
  fetchHotTags()  // 添加获取热门标签的调用
})

function selectTag(tagInfo) {
  console.log(tagInfo);
  if (activeTag.value === tagInfo.name) {
    activeTag.value = ''
    selectedField.value = ''  // 清空专业领域ID
  } else {
    activeTag.value = tagInfo.name
    selectedField.value = tagInfo.id  // 设置专业领域ID
    currentPage.value = 1
  }
  refetch() // 添加重新请求数据
}
function clearTag() {
  activeTag.value = ''
  selectedField.value = ''  // 清空专业领域ID
  currentPage.value = 1 // 重置页码
  refetch() // 添加重新请求数据
}
function goToDetail(expert) {
  router.push(`/expert/${expert.id}`)
}

// 权限控制：只有 isAdmin 为 true 时显示新增专家按钮

// 处理筛选条件变化
const handleFilterChange = () => {
  currentPage.value = 1 // 重置页码
  refetch() // 重新请求数据
}

// 处理筛选条件重置
const handleFilterReset = () => {
  // 重置页码
  currentPage.value = 1
  // 重置标签筛选
  activeTag.value = ''
  // 重新获取数据
  refetch()
}

// 处理tab切换
const handleActiveTabChange = (type) => {
  activeTab.value = type
  sessionStorage.setItem('activeTab', type)
}

</script>

<style scoped>
.el-tag {
  margin-bottom: 4px;
}
.expert-card {
  box-shadow: 0 2px 12px 0 rgba(56, 112, 255, 0.06);
  border: 1.5px solid #e6eaf2;
  transition: box-shadow 0.2s, border 0.2s;
}
.expert-card:hover {
  box-shadow: 0 6px 24px 0 rgba(56, 112, 255, 0.13);
  border-color: #a3c8fa;
}
.avatar-ring {
  border-radius: 50%;
  padding: 4px;
  background: linear-gradient(135deg, #a3c8fa 0%, #e6f0fa 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}
.custom-pagination :deep(.el-pager li) {
  border-radius: 1.5rem;
  margin: 0 4px;
  font-size: 18px;
  min-width: 40px;
  height: 40px;
  line-height: 40px;
  color: #1765ad;
  transition: background 0.2s, color 0.2s;
}
.custom-pagination :deep(.el-pager li.active) {
  background: linear-gradient(90deg, #4f9cff 0%, #1765ad 100%);
  color: #fff;
  font-weight: bold;
  box-shadow: 0 2px 8px 0 rgba(56,112,255,0.10);
}
.custom-pagination :deep(.el-pager li):hover {
  background: #e6f0fa;
  color: #1765ad;
}
.filter-bar-container {
  /* 保证筛选区单行排列，内容溢出时横向滚动 */
  flex-wrap: nowrap !important;
  white-space: nowrap;
  overflow-x: auto;
  background: linear-gradient(120deg, rgba(250,253,255,0.85) 0%, rgba(242,246,252,0.95) 100%);
  backdrop-filter: blur(18px);
  border-radius: 2.5rem;
  border: 2.5px solid #e6eaf2;
  box-shadow: 0 8px 32px 0 rgba(56, 112, 255, 0.13);
  /* margin-bottom: 2rem; */
  /* padding: 2.2rem 2.5rem; */
  align-items: center;
  transition: box-shadow 0.2s, background 0.2s, border 0.2s;
  position: relative;
  gap: 1.5rem;
}
.filter-bar-beauty :deep(.el-input),
.filter-bar-beauty :deep(.el-select) {
  border-radius: 2rem !important;
  margin-right: 22px;
  min-width: 150px;
  font-size: 16px;
  background: #fafdff !important;
  transition: border 0.2s, box-shadow 0.2s, background 0.2s;
}
.filter-bar-beauty :deep(.el-input__wrapper),
.filter-bar-beauty :deep(.el-select .el-input__wrapper) {
  border-radius: 2rem !important;
  box-shadow: none;
  border: 1.5px solid #e6eaf2;
  background: #fff !important;
  transition: border 0.2s, box-shadow 0.2s, background 0.2s;
}
.filter-bar-beauty :deep(.el-input__wrapper:hover),
.filter-bar-beauty :deep(.el-select .el-input__wrapper:hover),
.filter-bar-beauty :deep(.el-input__wrapper.is-focus),
.filter-bar-beauty :deep(.el-select .el-input__wrapper.is-focus) {
  border-color: #4f9cff;
  box-shadow: 0 0 0 2px #e6f0fa;
  background: #f0f7ff !important;
}
.filter-bar-beauty :deep(.el-input__inner),
.filter-bar-beauty :deep(.el-select__selected-item) {
  color: #1765ad;
}
.add-btn {
  background: linear-gradient(90deg, #4f9cff 0%, #1765ad 100%);
  color: #fff;
  border-radius: 2rem;
  font-weight: bold;
  font-size: 16px;
  padding: 0 2rem;
  box-shadow: 0 2px 8px 0 rgba(56,112,255,0.13);
  border: none;
  transition: background 0.2s, color 0.2s;
  display: flex;
  align-items: center;
  height: 48px;
  letter-spacing: 1px;
}
.add-btn:hover {
  background: linear-gradient(90deg, #1765ad 0%, #4f9cff 100%);
  color: #fff;
}
@media (max-width: 900px) {
  .filter-bar-container {
    flex-direction: column;
    gap: 1.5rem;
    padding: 1.5rem 1rem;
    flex-wrap: wrap !important;
    white-space: normal;
    overflow-x: visible;
  }
  .add-btn {
    width: 100%;
    justify-content: center;
    margin-top: 1rem;
  }
}
.glass-blur {
  background: linear-gradient(90deg, #fafdffcc 0%, #f2f6fccf 100%) !important;
  backdrop-filter: blur(12px);
  border: 1.5px solid #e6eaf2;
  box-shadow: 0 8px 32px 0 rgba(56, 112, 255, 0.10);
}
.expert-list-area {
  background: linear-gradient(135deg, #fafdff 0%, #f2f6fc 100%);
  border-radius: 2.5rem;
  box-shadow: 0 4px 24px rgba(56,112,255,0.08);
  margin-bottom: 2rem;
  padding: .5rem 2rem;
  margin-left: 2rem;
}
.tab-switch-bar {
  margin-top: 20px;
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  max-width: 1200px;
  margin-left: auto;
  margin-right: auto;
  gap: 0; /* 按钮之间用分割线分隔 */
}
.tab-switch-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 700;
  color: #1765ad;
  background: linear-gradient(90deg, #fafdff 0%, #e3f0ff 100%);
  border: 2.5px solid #4f9cff;
  border-radius: 2.5rem;
  padding: 12px 48px;
  box-shadow: 0 4px 16px rgba(56,112,255,0.10);
  transition: 
    background 0.25s, 
    color 0.25s, 
    border 0.25s, 
    box-shadow 0.25s,
    transform 0.18s;
  letter-spacing: 1px;
  cursor: pointer;
  margin: 0 0.5rem;
  position: relative;
  z-index: 1;
  outline: none;
  overflow: hidden;
}

.tab-switch-btn .tab-icon {
  font-size: 22px;
  margin-right: 6px;
}

.tab-switch-btn.active {
  background: linear-gradient(90deg, #4f9cff 0%, #1765ad 100%);
  color: #fff;
  border-color: #1765ad;
  box-shadow: 0 6px 24px rgba(56,112,255,0.18);
  transform: translateY(-2px) scale(1.04);
}

.tab-switch-btn:not(.active):hover {
  background: #e3f0ff;
  color: #1765ad;
  border-color: #1765ad;
  box-shadow: 0 2px 12px rgba(56,112,255,0.13);
  transform: translateY(-1px) scale(1.02);
}

@media (max-width: 900px) {
  .tab-switch-bar {
    gap: 0;
    flex-direction: row;
    padding: 0 8px;
  }
  .tab-switch-btn {
    padding: 10px 18px;
    font-size: 15px;
    margin: 0 4px;
    min-width: 110px;
    justify-content: center;
  }
  .tab-switch-btn .tab-icon {
    font-size: 18px;
    margin-right: 4px;
  }
}
</style>
